package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"regexp"
	"video-hub/models/cache"
	"video-hub/models/mysql"
	"video-hub/pkg"

	"video-hub/videorpc/internal/svc"
	"video-hub/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 客户端手机号登录
func (l *LoginLogic) Login(in *videorpc.LoginRequest) (*videorpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	matchString, err := regexp.MatchString(`^1[3-9]\d{9}$`, in.Phone)
	if err != nil {
		return nil, err
	}
	if !matchString {
		return nil, errors.New("请输入正确的手机号")
	}
	var findUser mysql.User
	err = findUser.FindUserByPhone(mysql.DB, in.Phone)
	if err != nil {
		return nil, err
	}
	if findUser.ID == 0 {
		user := &mysql.User{
			Phone:     in.Phone,
			Password:  pkg.Md5(in.Password),
			NickName:  fmt.Sprintf("游客_%d", rand.Intn(10000)),
			HeadImage: "http://t4kaqyl71.hn-bkt.clouddn.com/A5CCBC86D859D90E6483736AC2BF3A32.jpg",
		}
		err = user.UserAdd(mysql.DB)
		if err != nil {
			return nil, errors.New("注册失败")
		}
		err = user.FindUserByPhone(mysql.DB, in.Phone)
		if err != nil {
			return nil, err
		}
	}
	if in.LoginType == 1 || in.LoginType == 2 {
		if in.LoginType == 1 {
			result, _ := cache.Rdb.Get(l.ctx, "smsCode_"+in.Phone).Result()
			if result == "" {
				return nil, errors.New("验证码已过期，请重新获取")
			}
			if result != in.SmsCode {
				return nil, errors.New("验证码不正确,请重试")
			}
			if findUser.Status == 1 {
				return nil, errors.New("账号已禁用，请联系管理员")
			}
		}
		if in.LoginType == 2 {
			if pkg.Md5(in.Password) != findUser.Password {
				return nil, errors.New("密码不正确")
			}
			if findUser.Status == 1 {
				return nil, errors.New("账号已禁用，请联系管理员")
			}
		}
	} else {
		return nil, errors.New("请选择正确的登录方式")
	}

	return &videorpc.LoginResponse{
		UserId: int64(findUser.ID),
	}, nil
}
